<template>
  <el-card
    class="mt20"
    shadow="never"
  >
    <template #header>
      <div>
        <span>{{ $t("form.todoForm.todoTask") }}</span>
        <span class="desc-text ml10">{{ $t("form.todoForm.todoTaskDesc") }}</span>
      </div>
    </template>
    <el-form
      label-position="left"
      inline
      size="default"
    >
      <el-form-item :label="$t('form.todoForm.taskName')">
        <el-input
          v-model="queryParams.name"
          clearable
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          size="default"
          icon="ele-Search"
          @click="queryTodoFormTaskList"
        >
          {{ $t("formI18n.all.search") }}
        </el-button>
      </el-form-item>
    </el-form>
    <div class="publish-content">
      <div>
        <el-button
          plain
          type="primary"
          size="default"
          @click="handleAddTask"
        >
          {{ $t("form.todoForm.addTask") }}
        </el-button>
        <el-button
          plain
          type="success"
          size="default"
          @click="showConfigTemplate"
        >
          {{ $t("form.todoForm.template") }}
        </el-button>
      </div>
      <el-divider />
      <el-table
        v-loading="loading"
        :data="todoFormTodoList"
        max-height="50vh"
      >
        <el-table-column
          align="center"
          :label="$t('form.todoForm.taskName')"
          prop="name"
          show-overflow-tooltip
        >
          <template #default="scope">
            {{ scope.row.name }}
            <div class="w100">
              <el-progress
                :percentage="scope.row.percentageValue"
                style="margin: 0 auto"
              >
                {{ scope.row.completedCount || 0 }} / {{ scope.row.totalCount || 0 }}
              </el-progress>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          :label="$t('form.todoForm.createTime')"
          prop="createTime"
          width="180"
          show-overflow-tooltip
        />
        <el-table-column
          align="center"
          class-name="small-padding fixed-width"
          :label="$t('form.public.assignedUsersOperation')"
        >
          <template #default="scope">
            <el-button
              link
              type="info"
              @click="handleOpenDetail(scope.row)"
            >
              {{ $t("form.todoForm.details") }}
            </el-button>
            <el-button
              link
              type="primary"
              @click="handleUpdateTask(scope.row)"
            >
              {{ $t("form.todoForm.edit") }}
            </el-button>
            <el-button
              link
              type="success"
              @click="handleSendTaskReminder(scope.row)"
            >
              {{ $t("form.todoForm.reminder") }}
            </el-button>
            <el-button
              link
              type="danger"
              @click="handleDeleteTask(scope.row)"
            >
              {{ $t("formI18n.all.delete") }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="total > 0"
        v-model:limit="queryParams.size"
        v-model:page="queryParams.current"
        :total="total"
        @pagination="queryTodoFormTaskList"
      />
    </div>
    <el-dialog
      v-model="dialogVisible"
      :title="$t('form.todoForm.task')"
      width="800"
    >
      <el-form
        :model="form"
        :rules="rules"
        label-width="auto"
        ref="formRef"
      >
        <el-form-item
          :label="$t('form.todoForm.taskName')"
          prop="name"
        >
          <el-input
            v-model="form.name"
            size="default"
          />
        </el-form-item>
        <el-form-item
          :label="$t('form.todoForm.taskDescription')"
          prop="description"
        >
          <el-input
            v-model="form.description"
            size="default"
            type="textarea"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">{{ $t("common.cancel") }}</el-button>
          <el-button
            type="primary"
            @click="handleSubmit"
          >
            {{ $t("common.confirm") }}
          </el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog
      v-model="detailDialogVisible"
      :title="$t('form.todoForm.details')"
      width="1200"
    >
      <div class="flex">
        <assign-button-list
          :form-key="queryParams.formKey"
          :task-id="tdQueryParams.taskId"
          @refresh="handleAssignSuccess"
        />
        <el-button
          plain
          class="ml20"
          size="default"
          type="danger"
          :disabled="tdIds.length === 0"
          @click="handleDeleteAssignUser()"
        >
          {{ $t("formI18n.all.delete") }}
        </el-button>
        <el-button
          plain
          size="default"
          type="success"
          @click="handleExportList"
        >
          {{ $t("form.todoForm.exportList") }}
        </el-button>
      </div>
      <el-form
        class="mt20"
        label-position="left"
        inline
        size="default"
      >
        <el-form-item :label="$t('form.todoForm.userAccount')">
          <el-input
            v-model="tdQueryParams.userName"
            clearable
          />
        </el-form-item>
        <el-form-item :label="$t('form.todoForm.userNickname')">
          <el-input
            v-model="tdQueryParams.nickName"
            clearable
          />
        </el-form-item>
        <el-form-item :label="$t('form.todoForm.taskStatus')">
          <el-radio-group v-model="tdQueryParams.status">
            <el-radio-button :value="null">{{ $t("form.todoForm.allStatus") }}</el-radio-button>
            <el-radio-button :value="0">{{ $t("form.public.unfinished") }}</el-radio-button>
            <el-radio-button :value="1">{{ $t("form.public.finished") }}</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            size="default"
            icon="ele-Search"
            @click="queryTodoFormList"
          >
            {{ $t("formI18n.all.search") }}
          </el-button>
        </el-form-item>
        <el-form-item :label="$t('form.todoForm.completionTime')">
          <el-date-picker
            v-model="tdQueryParams.beginDateTime"
            type="datetime"
            size="default"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            :placeholder="$t('form.todoForm.startTime')"
          />

          <el-date-picker
            class="ml10"
            v-model="tdQueryParams.endDateTime"
            type="datetime"
            size="default"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            :placeholder="$t('form.todoForm.endTime')"
          />
        </el-form-item>
      </el-form>
      <el-table
        v-loading="tdLoading"
        :data="todoFormList"
        max-height="50vh"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          align="center"
          type="selection"
          width="55"
        />
        <el-table-column
          align="center"
          :label="$t('form.public.username')"
          prop="userName"
        />
        <el-table-column
          align="center"
          :label="$t('form.public.nickName')"
          prop="nickName"
        />
        <el-table-column
          align="center"
          :label="$t('form.public.status')"
          prop="status"
        >
          <template #default="scope">
            <el-tag
              v-if="scope.row.status === 0"
              type="danger"
            >
              {{ $t("form.public.unfinished") }}
            </el-tag>
            <el-tag
              v-else
              type="success"
            >
              {{ $t("form.public.finished") }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          :label="$t('form.public.completeTime')"
          prop="updateTime"
        />
        <el-table-column
          align="center"
          :label="$t('form.public.assignTime')"
          prop="createTime"
        />
        <el-table-column
          align="center"
          class-name="small-padding fixed-width"
          :label="$t('form.public.assignedUsersOperation')"
        >
          <template #default="scope">
            <el-button
              link
              type="primary"
              @click="handleSendTodoReminder(scope.row)"
            >
              {{ $t("form.todoForm.reminder") }}
            </el-button>
            <el-button
              link
              type="success"
              @click="handeCopyLink(scope.row)"
            >
              {{ $t("form.todoForm.link") }}
            </el-button>
            <el-button
              link
              type="danger"
              @click="handleDeleteAssignUser(scope.row)"
            >
              {{ $t("formI18n.all.delete") }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="total > 0"
        v-model:limit="tdQueryParams.size"
        v-model:page="tdQueryParams.current"
        :total="tdTotal"
        @pagination="queryTodoFormList"
      />
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="detailDialogVisible = false">{{ $t("common.cancel") }}</el-button>
        </div>
      </template>
    </el-dialog>
    <config-template
      ref="configTemplateRef"
      :fields="msgConfigFields"
      @submit="handleSaveMsgTemplateConfig"
      :title="$t('form.configParams.configTemplateVariables')"
    />
  </el-card>
</template>

<script setup name="TodoFormTask" lang="ts">
import { onMounted, reactive, ref } from "vue";
import {
  addTaskTodo,
  delTaskTodo,
  delTodo,
  exportTaskTodo,
  listAllTodo,
  listTaskTodo,
  remindTodo,
  TodoFormTask,
  updateTaskTodo
} from "@/api/project/todo";
import { useRoute } from "vue-router";
import { i18n } from "@/i18n";
import type { FormInstance, FormRules } from "element-plus";
import { MessageBoxUtil, MessageUtil } from "@/utils/messageUtil";
import AssignButtonList from "./AssignButtonList.vue";
import ConfigTemplate from "./ConfigTemplate.vue";
import { getBaseUrlPath } from "@/utils/auth";
import { storeToRefs } from "pinia";
import { useFormInfo } from "@/stores/formInfo";
import { removeHtmlTag } from "@/views/formgen/utils";
import { getExtSettingByType, saveExtSetting } from "@/api/project/extSetting";
import { FieldItem } from "@/api/project/form";
import { download } from "@/utils/tduck";

const total = ref(0);

const queryParams = reactive({
  current: 1,
  size: 10,
  formKey: "",
  name: ""
});

const route = useRoute();

const configTemplateRef = ref<any>(null);

const showConfigTemplate = () => {
  getExtSettingByType("todoMsgTemplate", route.query.key as string).then(res => {
    configTemplateRef.value!.show(res.data?.settings ? JSON.parse(res.data.settings) : {});
  });
};

const handleSaveMsgTemplateConfig = async (val: any) => {
  await saveExtSetting({
    formKey: route.query.key as string,
    settings: JSON.stringify(val),
    type: "todoMsgTemplate"
  });
  MessageUtil.success(i18n.global.t("formI18n.all.success"));
};

const queryTodoFormTaskList = () => {
  loading.value = true;
  // 查询
  queryParams.formKey = route.query.key as string;
  listTaskTodo(queryParams).then(response => {
    todoFormTodoList.value = response.data.records;
    total.value = response.data.total;
    loading.value = false;
  });
};

onMounted(() => {
  queryTodoFormTaskList();
});

const handleUpdateTask = (row: TodoFormTask) => {
  form.value = { ...row };
  dialogVisible.value = true;
};

const handleDeleteTask = (row: TodoFormTask) => {
  MessageBoxUtil.confirm(i18n.global.t("formI18n.all.deleteConfirmation"), () => {
    delTaskTodo({ id: row.id }).then(() => {
      MessageUtil.success(i18n.global.t("formI18n.all.success"));
      queryTodoFormTaskList();
    });
  });
};

const tdIds = ref<number[]>([]);

const handleSelectionChange = (selection: TodoFormTask[]) => {
  tdIds.value = selection.map((item: TodoFormTask) => item.id as number);
};

const todoFormTodoList = ref<TodoFormTask[]>([]);

const loading = ref(false);

const handleAddTask = () => {
  form.value = {};
  dialogVisible.value = true;
};

const dialogVisible = ref(false);

const form = ref<TodoFormTask>({});

const rules = reactive<FormRules<TodoFormTask>>({
  name: [{ required: true, message: i18n.global.t("form.todoForm.enterTaskName"), trigger: "blur" }]
});
const formRef = ref<FormInstance>();

const handleSubmit = () => {
  formRef.value!.validate(async (valid: boolean) => {
    form.value.formKey = route.query.key as string;
    if (valid) {
      let res = null;
      if (!form.value.id) {
        res = await addTaskTodo(form.value);
      } else {
        res = await updateTaskTodo(form.value);
      }
      dialogVisible.value = false;
      queryTodoFormTaskList();
      MessageUtil.success(i18n.global.t("common.saveSuccess"));
      if (!form.value.id) {
        handleOpenDetail(res.data as TodoFormTask);
      }
    }
  });
};

const detailDialogVisible = ref(false);

const tdLoading = ref(false);
const todoFormList = ref([]);
const tdTotal = ref(0);
const tdQueryParams = ref({
  current: 1,
  size: 10,
  formKey: "",
  userName: "",
  nickName: "",
  taskId: 0,
  status: null,
  beginDateTime: null,
  endDateTime: null
});

const handleAssignSuccess = async () => {
  await queryTodoFormList();
  // 更新当前的
  const row = todoFormTodoList.value.find((item: TodoFormTask) => item.id === tdQueryParams.value.taskId);
  if (row) {
    row.totalCount = tdTotal.value;
  }
};

const handleOpenDetail = (row: TodoFormTask) => {
  tdQueryParams.value = {
    current: 1,
    size: 10,
    formKey: route.query.key as string,
    userName: "",
    nickName: "",
    taskId: row.id as number,
    status: null,
    beginDateTime: null,
    endDateTime: null
  };
  queryTodoFormList();
  detailDialogVisible.value = true;
};

const handleDeleteAssignUser = (row?: any) => {
  const ids = row ? [row.id] : tdIds.value;
  MessageBoxUtil.confirm(i18n.global.t("formI18n.all.deleteConfirmation"), () => {
    delTodo({ dataIdList: ids, formKey: queryParams.formKey }).then(() => {
      MessageUtil.success(i18n.global.t("formI18n.all.success"));
      queryTodoFormList();
    });
  });
};

const queryTodoFormList = async () => {
  tdLoading.value = true;
  // 查询
  const response = await listAllTodo(tdQueryParams.value);
  todoFormList.value = response.data.records;
  tdTotal.value = response.data.total;
  tdLoading.value = false;
};

const formInfoStore = useFormInfo();
const { currentFormName } = storeToRefs(formInfoStore);

// 给task下全部发送催办消息
const handleSendTaskReminder = (row: TodoFormTask) => {
  MessageBoxUtil.confirm(i18n.global.t("form.todoForm.confirmReminderAllUsers"), () => {
    remindTodo({
      formKey: queryParams.formKey,
      id: row.id as number,
      type: 1,
      params: {
        formName: removeHtmlTag(currentFormName.value),
        taskId: row.id,
        link: getBaseUrlPath() + "/s/" + queryParams.formKey + "?tid=" + row.id
      }
    }).then(() => {
      MessageUtil.success(i18n.global.t("form.todoForm.reminderSuccess"));
    });
  });
};

// 给task下全部发送催办消息
const handleSendTodoReminder = (row: TodoFormTask) => {
  MessageBoxUtil.confirm(i18n.global.t("form.todoForm.confirmReminder"), () => {
    remindTodo({
      formKey: queryParams.formKey,
      id: row.id as number,
      type: 2,
      params: {
        taskId: tdQueryParams.value.taskId,
        formName: removeHtmlTag(currentFormName.value),
        link: getBaseUrlPath() + "/s/" + queryParams.formKey + "?tid=" + tdQueryParams.value.taskId
      }
    }).then(() => {
      MessageUtil.success(i18n.global.t("form.todoForm.reminderSuccess"));
    });
  });
};

const handeCopyLink = (row: TodoFormTask) => {
  const link = getBaseUrlPath() + "/s/" + queryParams.formKey + "?tid=" + row.id;
  navigator.clipboard.writeText(link);
  MessageUtil.success(i18n.global.t("form.todoForm.copySuccess"));
};

const handleExportList = () => {
  exportTaskTodo(tdQueryParams.value).then(response => {
    download(response, i18n.global.t("form.todoForm.details"));
  });
};

const msgConfigFields = ref<FieldItem[]>([
  {
    label: i18n.global.t("form.todoForm.writeLink"),
    value: "link"
  },
  {
    label: i18n.global.t("form.todoForm.userNickName"),
    value: "userNickName"
  },
  {
    label: i18n.global.t("form.todoForm.formName"),
    value: "formName"
  },
  {
    label: i18n.global.t("form.todoForm.uniqueId"),
    value: "uniqueKey"
  }
]);
</script>

<style lang="scss" scoped>
.repeat-type-select {
  width: 100px;
}
</style>
